<template>
  <div class="indicator-swiper-wrap">
    <transition name="fade">
      <div @touchend="end" @touchstart="start" @touchmove="move" class="swiper">
        <div
          @dragstart.prevent
          @click="chooseItem(item, index)"
          v-for="(item, index) in imgs"
          :style="config5[index]"
          :key="index"
          class="swiper-item"
          :class="[index==currentIndex?'swiper-item-active':'','swiper-item-'+item.akaName]"
        >
          <div class="item-wrap">
            <p class="title">{{ item.index }}</p>
            <p class="info">指标数</p>
            <p class="num">{{ item.indexNum }}</p>

            <div class="warn" v-if="item.abnormalIndexNum>0">
              <van-icon name="warning-o" />
              <span>{{ item.abnormalIndexNum }}</span>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import HomeServe from '@/api/home'
defineOptions({
  name: 'IndicatorSwiper'
})

const emit = defineEmits(['switch'])

const router = useRouter()

const currentIndex = ref(1); //当前中间imgs数组中index
const activeItemIndex = ref(2); //列表第2个默认为中间选中状态
const centerInfo = ref(""); //当前中间信息
const imgs = ref([]);

const filterName = (name: string) => {
  let icon = ""
  switch (name) {
    case '公共服务':
      icon = 'gonggongfuwu';
      break;
    case '生态环保':
      icon = 'shengtaihuanbao';
      break;
    case '社会治理':
      icon = 'shehuizhili';
      break;
    case '市场监管':
      icon = 'shichangjianguan';
      break;
    case '经济调节':
      icon = 'jingjitiaojie';
      break;
  }
  return icon
}

const chooseItem = (item) => {
  router.push({
    path: '/KeyIndicator',
    query: {
      type: item.index
    }
  })
}

//获取重点指标
const getKeyIndexNumber = () => {
  HomeServe.getKeyIndexNumber().then(res => {
    res.data.forEach(ele=>{
      ele.akaName = filterName(ele.index);
    })
    res.data.push({
      index: '',
      indexNum: 0,
      abnormalIndexNum: 0,
      akaName: ''
    })

    imgs.value = shunxuFunction(res.data,'index')
  })
}
getKeyIndexNumber()


//按照指定顺序排序
const shunxuFunction = (originalArr, property) => {
  let ruleList = ['经济调节', '公共服务', '生态环保', '社会治理', '市场监管']
  let ruleArr = ruleList.reverse()
  return originalArr.sort((a, b) => {
    if (property) {
      return ruleArr.indexOf(b[property]) - ruleArr.indexOf(a[property])
    } else {
      return ruleArr.indexOf(b) - ruleArr.indexOf(a)
    }
  })
}

const startY = ref(0);
const startX = ref(0);
const endY = ref(0);
const endX = ref(0);
const config5 = ref([
  {
    id: "A",
    position: "absolute",
    left: "0",
    opacity: 1,
    zIndex: 1,
    transition: ".4s",
  },
  {
    id: "center",
    position: "absolute",
    left: "33vw",
    opacity: 1,
    zIndex: 2,
    transition: ".4s",
  },
  {
    id: "C",
    position: "absolute",
    left: "66.2vw",
    opacity: 1,
    zIndex: 3,
    transition: ".4s",
  },
  {
    id: "D",
    position: "absolute",
    left: "104vw",
    opacity: 1,
    zIndex: 1,
    transition: ".4s",
  },
  {
    id: "E",
    position: "absolute",
    left: "135vw",
    opacity: 1,
    zIndex: 1,
    transition: ".4s",
  }
]);

const addCardStyle = () => {
  if (imgs.value.length > 4) {
    let addtime = imgs.value.length - 4;
    for (let i = 0; i < addtime; i++) {
      config5.value.push({
        id: "last",
        position: "absolute",
        left: 12.2+((i+1)*3.2)+"rem",
        opacity: 1,
        zIndex: 1,
        transition: ".4s",
      });
    }
  }
}
// 阻止touchmove的横向默认事件（ios快捷操作会关闭页面）
const stopDefault = (event) => {
  let differenceY = endY.value - startY.value;
  let differenceX = endX.value - startX.value;
  if (Math.abs(differenceX) > Math.abs(differenceY)) {
    event.preventDefault();
  }
}
// 连续滑动
const move = (event) => {
  endY.value = event.changedTouches[0].clientY;
  endX.value = event.changedTouches[0].clientX;
  stopDefault(event);
  // 如果是滑动，注解（223行到231行）这段。如果是连续滑动，放开（223行到231行）注解
  let interval = endX.value - startX.value;
  if (interval > 40) {
    startX.value = endX.value;
    prev();
  }
  if (interval < -40) {
    startX.value = endX.value;
    next();
  }
}
// 滑动上一个
const prev = () => {
  if(currentIndex.value < activeItemIndex.value){  //前面没有了 
    return
  }
  config5.value.push(config5.value.shift());
  currentIndex.value = currentIndex.value - 1;
  if (currentIndex.value < 0) {
    currentIndex.value = imgs.value.length - 1;
  }
  centerCard();
  centerIndex("prev");
}
// 滑动下一个
const next = () => {
  if((currentIndex.value+activeItemIndex.value) >= imgs.value.length){   //后面没有了
    return
  }
  config5.value.unshift({
    id: "pre",
    position: "absolute",
    left: 0-(currentIndex.value*3.2)+"rem",
    opacity: 0,
    zIndex: 1,
    transition: ".4s",
  });
  currentIndex.value = currentIndex.value + 1;
  if (currentIndex.value > imgs.value.length - 1) {
    currentIndex.value = 0;
  }
  centerCard();
  centerIndex("next");
}
// 开始移动端滑动屏幕
const start = (event) => {
  startX.value = event.changedTouches[0].clientX;
  startY.value = event.changedTouches[0].clientY;
}
const end = () => {
  
}
// 当前imgs在位置上的index（并非img数组的index）
const centerIndex = (val: string) => {
  if (val == "prev") {
    for (let val of imgs.value) {
      if (val.indexs == imgs.value.length - 1) {
        val.indexs = 0;
      } else {
        val.indexs = val.indexs + 1;
      }
    }
  } else {
    for (let val of imgs.value) {
      if (val.indexs == 0) {
        val.indexs = imgs.value.length - 1;
      } else {
        val.indexs = val.indexs - 1;
      }
    }
  }
}
// 计算中间卡片信息
const centerCard = () => {
  centerInfo.value = imgs.value[currentIndex.value];
}

centerCard(); // 获取中间卡片信息
addCardStyle(); // 加入样式位置的index
</script>


<style lang="less" scoped>
.indicator-swiper-wrap {
  margin-left: 13px;
  margin-bottom: 12px;
  padding: 12px 0 12px 12px;
  border-radius: 8px 0 0 8px;
  background: rgba(255,255,255,1);
  .swiper {
    width: 100%;
    height: 100px;
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;
    .swiper-item{
      padding: 13px;
      opacity: 0;
      width: 87px;
      height: 71px;
      background: url("@/assets/home/bg-gonggongfuwu.png") no-repeat center center;
      background-size: 100% 100%;
      color: #00000099;
      font-size: 12px;
      cursor: grab;
      .item-wrap{
        position: relative;
        width: 100%;
        height: 100%;
      }
      .title{      
        font-size: 14px;
        color: #000;
        font-weight: 900;
      }
      .info{
        margin: 12px 0 8px;
      }
      .num{      
        font-size: 26px;
        color: #212121;
        font-family: "DINPro";
        font-weight: 900;
      }
      .warn{
        border-radius: 10px 6px 0px 10px;
        background: linear-gradient(90deg, #F52F45 0%, #F55F5F 100%);
        min-width: 30px;
        height: 17px;
        position: absolute;
        right: -13px;
        top: -13px;
        width: max-content;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        padding: 0 4px;
        span{
          font-size: 12px;
          margin-left: 4px;
        }
      }
      &.swiper-item-active{
        
      }
      &.swiper-item-gonggongfuwu{
        background: url("@/assets/home/bg-gonggongfuwu.png") no-repeat center center;
        background-size: 100% 100%;
      }
      &.swiper-item-jingjitiaojie{
        background: url("@/assets/home/bg-jingjitiaojie.png") no-repeat center center;
        background-size: 100% 100%;
      }
      &.swiper-item-shehuizhili{
        background: url("@/assets/home/bg-shehuizhili.png") no-repeat center center;
        background-size: 100% 100%;
      }
      &.swiper-item-shengtaihuanbao{
        background: url("@/assets/home/bg-shengtaihuanbao.png") no-repeat center center;
        background-size: 100% 100%;
      }
      &.swiper-item-shichangjianguan{
        background: url("@/assets/home/bg-shichangjianguan.png") no-repeat center center;
        background-size: 100% 100%;
      }
      &:last-child{
        display: none;
      }
    }
  }

}
</style>